<?php


namespace app\MiniHome\AuthManage;

use app\model\MiniHome\AuthManage\LoginModel;
use Webman\Http\Request;

class LoginController
{
    //预登录
    public function preLogin(Request $request)
    {
        $relData = LoginModel::getOpenidSessionKeyNew($request->all());
        if ($relData['code'] != RETURN_SUCCESS) {
            error_log(date('Y-m-d H:i:s') . ' request:' . json_encode($request, JSON_UNESCAPED_UNICODE) . ' 预登陆=> ' . "\r\n\r\n", 3, env('LOG_ROOT') . '/preLoginWeiXin-' . date('Y-m-d') . '.log');
        }
        return ApiReturn($relData);
//        return response(ApiReturn($relData));
    }





    public function login(Request $request)
    {
        $code = $request->input('code','');

        $relData = LoginModel::LoginUser($code);
        return ApiReturn($relData);
    }
    /**
     * 更新当前TOKEN
     * @return false|string
     * @throws \Exception
     */
    public function updateToken()
    {
        $relData = LoginModel::updateToken(APP_USER_TOKEN);
        return ApiReturn($relData);
    }

    /**
     * 退出登录
     * @return false|string
     * @throws \Exception
     */
    public function loginOut()
    {
        $relData = LoginModel::LoginOut(APP_USER_TOKEN);
        return ApiReturn($relData);
    }

    /**
     * 获取用户信息
     * @return false|string
     * @throws \Exception
     */
    public function getUserInfo()
    {
        $userInfoObj = LoginModel::getUserInfo(APP_USER_TOKEN);
        if ($userInfoObj['code'] != RETURN_SUCCESS) {
            return ApiReturn($userInfoObj);
        }

        $userObj = $userInfoObj['data'];
        unset($userObj['authList'], $userObj['uid']);
        return ApiReturn(RETURN_SUCCESS, "获取成功", $userObj);
    }

    /**
     * 用户注册
     * @param Request $request
     * @return false|string
     * @throws \Exception
     */
    public function register(Request $request) {
        $loginCode = $request->input('loginCode', '');
        $phoneCode = $request->input('phoneCode', '');

        $relData = LoginModel::register($loginCode, $phoneCode);
        return ApiReturn($relData);
    }

    /**
     * 获取微信手机号
     * @param Request $request
     * @return false|string
     * @throws \Exception
     */
    public function getWeChatPhoneNumber(Request $request) {
        $code = $request->input('code', '');
        $relData = LoginModel::getWeChatPhoneNumber(APP_USER_TOKEN, $code);
        return ApiReturn($relData);
    }

    /**
     * 解密微信加密数据
     * @param Request $request
     * @return false|string
     * @throws \Exception
     */
    public function decryptData(Request $request) {
        $encryptedData = $request->input('encryptedData', '');
        $iv = $request->input('iv', '');
        $relData = LoginModel::decryptData(APP_USER_TOKEN, $encryptedData, $iv);
        return ApiReturn($relData);
    }
}